<?php
/**
 * Created by PhpStorm.
 * User: mac1
 * Date: 16/6/10
 * Time: 上午10:32
 */

namespace app\admin\controller;
use app\admin\model\Admintype;
use app\admin\model\Campus;
use app\admin\validate\AdminValidate;
use think\Db;
use app\admin\model\Admin;

class ApimyController extends CommonController
{
    /*---------------我的start---------------*/

    /**
     * getPersonData 获取个人信息(我的或者他人的，他人的传uid)
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return string
     */
    public function getPersonData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        //=================================
        $b = array();
        $b['b_user_id'] = $user_id;
        //=================================
        $who = 0;//不是你的好友
        $friend_id = 0;//申请的id
        if(isset($uid)){
            //=======是不是我的好友======
            $whofri = $this->getFriendStatus($uid,$user_id);
            $who = $whofri['who'];
            $friend_id = $whofri['friend_id'];
            //========end=====
            $user_id = $uid;
        }else{
            $uid = $user_id;
        }
        $data = Db::table('ew_u_user')
            ->where('user_id',$user_id)
//            ->field('user_id,user_username,user_image,user_phone,user_content')
            ->find();
        if($data['ew_life_photos']){
            $imgs = trim($data['ew_life_photos']);
            $data['ew_life_photos'] = explode(',',$imgs);
        }
        //==================
        $black = 0;
        $b['b_black_uid'] = $uid;
        $have = Db::table('ew_black')->where($b)->find();
        if($have){$black = 1;}
        //====================
        return json_encode(['status'=>200,'msg'=>$data,'who'=>$who,'friend_id'=>$friend_id,'black'=>$black]);
    }
    /**
     * getPersonData 单独获取个人信息(我的或者他人的，他人的传uid)的历史发布：秀和圈
     * page  uid
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return string
     */
    public function getPersonDataHistory(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if(!isset($uid)){$uid = $user_id;}
        $field = 'circle_id,user_id,circle_content,circle_message,circle_zan,circle_image,circle_createtime,circle_url';
        $field .= ',user_username,user_image,circle_createtime time';
        $datac = Db::table('ew_circle')->alias('c')
            ->join('ew_u_user uu','c.circle_user_id=uu.user_id','LEFT')
            ->where('circle_user_id',$uid)
            ->field($field)
            ->order('time DESC')
            ->select();

        $datah = Db::table('ew_hot')->alias('h')
            ->join('ew_u_user u','h.h_user_id=u.user_id','LEFT')
            ->where('h_user_id',$uid)
            ->field('h_id,h_url,h_title,h_time time,h_num,h_zan,h_message,user_id,user_username,user_image')
            ->order('time DESC')
            ->select();
        $dataall = array_merge($datac,$datah);
		if($dataall){
			//        ---------------------------------
        $sort = array(
            'direction' => 'SORT_DESC', //排序顺序标志 SORT_DESC 降序；SORT_ASC 升序
            'field'     => 'time',       //排序字段
        );
        $arrSort = array();
        foreach($dataall AS $uniqid => $row){
            foreach($row AS $key=>$value){
                $arrSort[$key][$uniqid] = $value;
            }
        }
        if($sort['direction']){
            array_multisort($arrSort[$sort['field']], constant($sort['direction']), $dataall);
        }
//        ---------------------------------
        $start = ($page-1)*10;
        $data = array_slice($dataall,$start,10);
        if($data){
            foreach ($data as $k=>$v){
                $data[$k]['zan'] = 0;
                if(isset($v['circle_id'])){
                    $data[$k]['type'] = 1;
                    $data[$k]['circle_createtime'] = $v['time'];
                    if($v['circle_image']){
                        $data[$k]['circle_image'] = explode(',',$v['circle_image']);
                    }
                    $zan = Db::table('ew_circle_zan')
                        ->where('cz_user_id',$user_id)
                        ->where('cz_circle_id',$v['circle_id'])
                        ->find();
                    if($zan){
                        $data[$k]['zan'] = 1;
                    }
                }else{
                    $data[$k]['type'] = 2;
                    $data[$k]['h_time'] = $v['time'];
                    $havezan = Db::table('ew_hot_zan')
                        ->where('cz_user_id',$user_id)
                        ->where('cz_hot_id',$v['h_id'])
                        ->find();
                    if($havezan){
                        $data[$k]['zan'] = 1;
                    }
                }
            }
        }
		}else{
			$data = array();
		}

        return json_encode(['status'=>200,'msg'=>$data]);
    }

    /**
     * updatePersonData 修改个人信息
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return string
     */
    public function updatePersonData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if(isset($username)){
            $data['user_username'] = $username;
        }
        //=============更新图片==================
            $dir = $_SERVER['DOCUMENT_ROOT'];
            $url =  "http://".$_SERVER['HTTP_HOST'];

            if(!empty($_FILES['image']['tmp_name'])){
                //=======重命名=====
                $rand = date('YmdHis').rand(100000,999999);
                $exe = explode('.',$_FILES['image']['name']);
                $index = count($exe);
                $exe = $exe[$index-1];
                $_FILES['image']['name'] = $rand . '.' .$exe;
                //=======================
                if(move_uploaded_file($_FILES['image']['tmp_name'],"{$dir}/mang/avatar/{$_FILES['image']['name']}")){
                    $data['user_image'] = "{$url}/mang/avatar/{$_FILES['image']['name']}";
                    if($_FILES['image']['size'] > 1024*300){
                        $this->image_png_size_add("$dir/mang/avatar/{$_FILES['image']['name']}","$dir/mang/avatar/{$_FILES['image']['name']}");
                    }
                }else{
                    return json_encode(['status'=>0,'msg'=>'图片保存失败']);
                }
            }
        //=============end=====================
        if(isset($content)){
            $data['user_content'] = $content;
        }
        if(isset($user_gender)){
            $data['user_gender'] = $user_gender;
        }
        if(isset($user_age)){
            $data['user_age'] = $user_age;
        }
        if(isset($user_like)){
            $data['user_like'] = $user_like;
        }
        if(isset($user_qq)){
            $data['user_qq'] = $user_qq;
        }
        if(isset($user_wx)){
            $data['user_wx'] = $user_wx;
        }
        if(isset($user_photos) && $user_photos){
            $data['ew_life_photos'] = trim($user_photos,',');
        }

        $res = Db::table('ew_u_user')
            ->where('user_id',$user_id)
            ->update($data);
        if($res){
            if(isset($user_photos) && $user_photos){
                return json_encode(['status' => 200, 'msg' => explode(',',$data['ew_life_photos'])]);
            }
            if(!empty($_FILES['image']['tmp_name'])) {
                return json_encode(['status' => 200, 'msg' => $data['user_image']]);
            }else{
                return json_encode(['status' => 200, 'msg' => "成功"]);
            }
        }else{
            return json_encode(['status'=>200,'msg'=>"修改失败！"]);
        }
    }
    /*---------------我的end---------------*/
    /**
     * 我的发布——职位
     * page（如果有搜索就传search）
     * @return string
     */
    public function myJobData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        if(isset($search)){$where['job_name'] = array('like',"%$search%");}//仅此行附带搜索
        $where['job_user_id'] = $user_id;
        $data = $this->getJobData(4,$where,$page);
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的发布——资讯
     * page（如果有搜索就传search）
     * @return string
     */
    public function myLifeData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        $where['life_user_id'] = $user_id;
        $where['life_new_type'] = array('in','1,2,3');
        $data = $this->getLifeData(1,$where,$page);
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的收藏——资讯
     * page（如果有搜索就传search）
     * type：1是三个发布，2是资讯
     * @return string
     */
    public function myLikeLifeData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $lids = Db::table('ew_attention_life')
            ->where('al_user_id',$user_id)
            ->column('al_life_id');
        $where = array();
        if($lids){
            $where['life_id'] = array('in',$lids);
        }
        $where['index_user_id'] = $user_id;
        if($type == 1){
            $where['life_new_type'] = array('in','1,2,3');
            $data = $this->getLifeData(1,$where,$page);
        }else{
            $where['life_new_type'] = 4;
            $data = $this->getLifeData(4,$where,$page);
        }

        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 我的发布——动态
     * page（如果有搜索就传search）
     * @return string
     */
    public function myCircleData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $where = array();
        if(isset($search)){$where['circle_content'] = array('like',"%$search%");}//仅此行附带搜索
        $where['circle_user_id'] = $user_id;
        $data = Db::table('ew_circle')
            ->where($where)
            ->order('circle_createtime DESC')
            ->limit(($page-1)*10,10)
            ->select();
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * 删除我发布的某一个动态
     * circle_id
     * @return string
     */
    public function myCircleDataDel(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if(!isset($type)){//旧的接口会没有此参，所以默认给成1，圈的
            $type = 1;
        }
        if($type != 1 && $type != 2){
            return json_encode(['status'=>0,'msg'=>'参数错误，未接收到类型']);
        }
        if($type == 1){
            $res = Db::table('ew_circle')
                ->where('circle_id',$circle_id)
                ->delete();
        }else{
            $res = Db::table('ew_hot')
                ->where('h_id',$circle_id)
                ->delete();
        }

        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }

    /**
     * 隐藏或者显示我的发布的职位
     * page（如果有搜索就传search）
     * @return string
     */
    public function updateMyJobStatus(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $status = Db::table('ew_job')->where('job_id',$job_id)->find()['job_status'];
        if($status == 1){
            $res = Db::table('ew_job')->where('job_id',$job_id)->update(['job_status'=>2]);
        }else{
            $res = Db::table('ew_job')->where('job_id',$job_id)->update(['job_status'=>1]);
        }
        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 删除我发布的职位：
     * job_id
     * @return string
     */
    public function deleteJob(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('ew_job')->where('job_id',$job_id)->delete();
        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }
    }
    /**
     * 我的收藏
     * type，page（如果有搜索就传search）
     * @return string
     */
    public function myLikeJobData(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $jids = Db::table('ew_attention_job')
            ->where('attention_user_id',$user_id)
            ->column('attention_job_id');
        $data = array();
        if($jids){
            $where = array();
            if(isset($search)){$where['job_name'] = array('like',"%$search%");}//仅此行附带搜索
            $where['job_id'] = array('in',$jids);
            $where['job_type'] = $type;
            $data = $this->getJobData($type,$where,$page);
        }
        return json_encode(['status'=>200,'msg'=>$data]);
    }
    /**
     * getFeedbackType 获取反馈建议类型数据
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return string
     */
    public function getFeedbackType(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = Db::table('ew_feedback_type')
            ->select();
        return json_encode(['status'=>200,'msg'=>$data]);
    }


    /**
     * feedback 提交反馈建议
     * @param $user_id 用户id
     * @param $time 时间
     * @param $value 加密值
     * @return string
     */
    public function feedback(){
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($feedback_type=="" || $feedback_content == "" || $feedback_weixin == ""){
            return json_encode(['satus'=>110,'msg'=>"信息不完整！"]);
        }
        $data = [
            'feedback_type'=>$feedback_type,
            'feedback_content'=>$feedback_content,
            'feedback_user_id'=>$user_id,
            'feedback_time'=>date("Y-m-d H:i:s"),
            'feedback_weixin'=>$feedback_weixin
        ];
        $res = Db::table('ew_feedback')->insert($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>"反馈成功！"]);
        }else{
            return json_encode(['status'=>110,'msg'=>"反馈失败！"]);
        }
    }

    /**
     * 给老汤的，聊天用
     */
    public function byIdsGetInfos()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $uids = trim($_POST['uids'],',');
        $pd = Db::table('ew_u_user')
            ->where('user_id','in',$uids)
            ->field('user_username,user_id,user_image')
            ->select();
        foreach ($pd as $k=>$v){
            $id = $v['user_id'];
            $one = Db::table('ew_friend')
                ->where('friend_user_id',$user_id)
                ->where('friend_good_user_id',$id)
                ->find();
            $two = Db::table('ew_friend')
                ->where('friend_user_id',$id)
                ->where('friend_good_user_id',$user_id)
                ->find();
            $pd[$k]['friend_status'] = 2;
            if($one && $one['friend_status']==1){
                $pd[$k]['friend_status'] = 1;//是好友
            }
            if($two && $two['friend_status']==1){
                $pd[$k]['friend_status'] = 1;//是好友
            }

        }
        return json_encode(['status'=>200,'msg'=>$pd]);
    }
    /**
     * 备用，我的所有好友列表（含搜索：search）:已经是好友了
     * 给老汤的，聊天用
     */
    public function myFriends()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if(isset($search)){$where['user_phone'] = $search;}//仅此行附带搜索
        $mygood1 = Db::table('ew_friend')
            ->where('friend_user_id',$user_id)
            ->where('friend_status',1)
            ->column('friend_good_user_id');
        $mygood2 = Db::table('ew_friend')
            ->where('friend_good_user_id',$user_id)
            ->where('friend_status',1)
            ->column('friend_user_id');
        $mygoods = array_merge($mygood1,$mygood2);
        $pd = array();
        if($mygoods){
            $where['user_id'] = array('in',$mygoods);
            $pd = Db::table('ew_u_user')
                ->where($where)
                ->field('user_username title,user_id employee_id,user_image imgPath,user_phone subTitle')
                ->select();
        }
        return json_encode(['status'=>200,'msg'=>$pd]);
    }
    /**
     * 备用，搜索手机号加人
     * 给老汤的，聊天用
     */
    public function searchFriend()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($search == ''){
            return json_encode(['status'=>200,'msg'=>null]);
        }
        $where['user_phone'] = $search;//搜索手机号加人
        $pd = array();
        $pd = Db::table('ew_u_user')
            ->where('user_phone',$search)
            ->field('user_username,user_id,user_image,user_phone')
            ->find();
        $whofri = $this->getFriendStatus($pd['user_id'],$user_id);
        return json_encode(['status'=>200,'msg'=>$pd,'who'=>$whofri['who'],'friend_id'=>$whofri['friend_id']]);
    }
    /**
     * 备用，加好友
     * uid
     * 给老汤的，聊天用
     */
    public function addFriend()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $whofri = $this->getFriendStatus($uid,$user_id);
        $who = $whofri['who'];
        if($who != 0 && $who != 3){
            $msg = $this->fiveWho($who);
            return json_encode(['status'=>0,'msg'=>$msg]);
        }
        if($who == 3){
            $fid = Db::table('ew_friend')
                ->where('friend_user_id',$user_id)
                ->where('friend_good_user_id',$uid)
                ->value('friend_id');
            Db::table('ew_friend')
                ->where('friend_user_id',$user_id)
                ->where('friend_good_user_id',$uid)
                ->update(['friend_status'=>2]);
        }else{
            $data = array();
            $data['friend_user_id'] = $user_id;
            $data['friend_good_user_id'] = $uid;
            $data['friend_status'] = 2;
            $fid = Db::name('friend')->insertGetId($data);
        }

        if($fid){
            /*-----------------加入消息表------------------*/
            $notice = array();
            $notice['n_where'] = 4;
                $time = date('Y-m-d H:i:s');
            $notice['n_time'] = $time;
            $notice['n_user_id'] = $uid;//申请谁
            $notice['n_reply_user_id'] = $user_id;//谁申请
            $notice['n_title'] = "申请加您为好友";
            $notice['n_circle_id'] = $fid;
            Db::table('ew_notice')->insert($notice);
            /*----------------------end------------------*/
            /*-----------推送和透传------------*/
            $name = Db::table('ew_u_user')->where('user_id',$user_id)->value('user_username');
            $this->sendJpush("$uid","{$name}申请您为好友",array('aa'=>'bb'),1,2);
            /*-----------end------------*/
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }

    }
    /**
     * 同意或者拒绝
     * friend_id,type(1是同意，3是拒绝)
     * 给老汤的，聊天用
     */
    public function agreeOrNotFriend()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('ew_friend')
            ->where('friend_id',$friend_id)
            ->update(['friend_status'=>$type]);
        if(isset($n_id)){
            Db::table('ew_notice')
                ->where('n_id',$n_id)
                ->update(['n_friend_status'=>$type]);
        }
        if($res){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }

    }
    /**
     * 删除好友
     * uid
     * 给老汤的，聊天用
     */
    public function deleteFriend()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $res = Db::table('ew_friend')
            ->where('friend_user_id',$user_id)
            ->where('friend_good_user_id',$uid)
            ->delete();
        $res2 = Db::table('ew_friend')
            ->where('friend_user_id',$uid)
            ->where('friend_good_user_id',$user_id)
            ->delete();

        if($res || $res2){
            return json_encode(['status'=>200,'msg'=>'操作成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'操作失败']);
        }

    }

    public function jubao()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        $data = array();
        $data['j_type'] = $type;
        $data['j_reason'] = trim($reason,',');
        $data['j_content'] = $content;
        $data['j_hc_id'] = $hcid;
        $data['j_user_id'] = $user_id;
        $data['j_time'] = date('Y-m-d H:i:s');
        $res = Db::table('ew_jubao')->insert($data);
        if($res){
            return json_encode(['status'=>200,'msg'=>'举报成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'举报失败']);
        }
    }
    public function blackList()
    {
        extract(input());
        $auth = $this->checkAll($user_id,$time,$value,$reqKey);
        if($auth == false){
            $returnData['status'] = 301;
            $returnData['msg'] = "Token失效！请重新登录！";
            return json_encode($returnData);
        }
        if($user_id == $uid){return json_encode(['status'=>1,'msg'=>'不能把自己拉黑']);}
        $data = array();
        $data['b_user_id'] = $user_id;
        $data['b_black_uid'] = $uid;
        $have = Db::table('ew_black')->where($data)->find();
        if($have){
            $res = Db::table('ew_black')->where($data)->delete();
        }else{
            $res = Db::table('ew_black')->insert($data);
        }
        if($res){
            return json_encode(['status'=>200,'msg'=>'成功']);
        }else{
            return json_encode(['status'=>0,'msg'=>'失败']);
        }
    }

}